package com.banmao.dynamicDS.aop;

import com.banmao.dynamicDS.aop.annotation.DataSource;
import com.banmao.dynamicDS.datasource.DatasourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
@Aspect
@Component
public class DataSourceAspect {

    /**
     * 给DataSource注解增加切面
     */
    @Pointcut("execution(* com.banmao..*(..)) && @annotation(com.banmao.dynamicDS.aop.annotation.DataSource)")
    public void dsPointCut() {

    }


    @Before(value = "dsPointCut()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (Objects.nonNull(dataSource)) {
            DatasourceContextHolder.setDS(DS.getName(dataSource.value()));
        } else {
            DatasourceContextHolder.setDS(DatasourceContextHolder.getDefaultdatasource());
        }
    }


    @AfterReturning("dsPointCut()")
    public void afterReturning(JoinPoint joinPoint) {
      /*  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);*/
        //移除数据源
        DatasourceContextHolder.popDS();
        //重新设置数据源
//        DynamicDataSourceContextHolder.setDataSourceName(DynamicDataSourceContextHolder.getDataSourceName());
    }

    @AfterThrowing(pointcut = "dsPointCut()",throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        //移除数据源
        DatasourceContextHolder.popDS();
    }

}
